<?php  
/**
 * 后台管理员操作处理代码
 */
// 引入项目初始化文件
require '../include/init.php';

// 获取操作的标识act的值
$act = isset($_GET['act']) ? $_GET['act'] : $_POST['act'];
// 处理非法操作
$action = ['logout', 'dologin','profile','doadd','doedit','del'];
if(!in_array($act, $action)){
	msg('非法操作');
}
// 处理登陆
if($act == 'dologin'){
	$username = trim($_POST['username']);
	$password = md5(trim($_POST['password']));
	if(empty($username) || empty($password)){
		msg('用户名或者密码不能为空！');
	}
	$sql = "select * from tk_admin where adusername = '$username' and  password ='$password'";

	$re = mysql_query($sql);
	if(mysql_num_rows($re)>0){
		$info = mysql_fetch_assoc($re);
		// 保存session
		$_SESSION['admin_id'] = $info['admin_id'];
		$_SESSION['admin_name'] = $info['adusername'];
		$_SESSION['last_login'] = $info ['last_time'];
		 $last_login = time();		
		$last_ip = $_SERVER['REMOTE_ADDR'];
		//更新信息
		$sql = "update tk_admin set last_time={$last_login},last_ip='{$last_ip}' where admin_id={$info['admin_id']}";
		mysql_query($sql);
		//跳转
		msg('登录成功！',"./index.php");
	}else{
		msg('用户名或者密码出错！');
	}
}
// 退出
else if($act == 'logout'){
	// $_SESSION = [];
	unset($_SESSION['admin_id']);
	unset($_SESSION['admin_name']);
	session_destroy();
	msg('退出成功！','login.php');

}
//管理员添加
else if ($act == 'doadd'){
	extract($_POST);
	$name = trim($user_name);
	$pwd = md5(trim($password));
	$email = trim($email);
	$rode_id = trim($rode_id);
	$last_time = time();
	$last_ip = $_SERVER['REMOTE_ADDR'];
	$sql = "insert into tk_admin (adusername,password,email,rode_id,last_time,last_ip) values('$name','$pwd','$email','$rode_id','$last_time','$last_ip')";
	mysql_query($sql);
	if(mysql_affected_rows()>0){
		msg('添加成功！','admin_list.php');
	}else{
		msg('添加失败！','admin_list_add.php');
	}

}
// 管理员编辑
else if($act == 'doedit'){
	extract($_POST);

	$name = trim($user_name);
	$pwd = md5(trim($password));
	$email = trim($email);
	//判断用户名是否存在
	$sql = "select * from tk_admin where adusername ='$name' and admin_id!='$id'";
	$res = mysql_query($sql);
	if(mysql_num_rows($res)>0){
		msg('用户名已经存在','admin_list_edit.php');
		exit;
	}
	//修改操作
	$sql = "UPDATE  tk_admin set adusername = '$name',password = '$pwd',email = '$email',rode_id ='$rode_id' where admin_id = '$id'";
	mysql_query($sql);
	if(mysql_affected_rows()>0){
		msg('修改成功！','admin_list.php');

	}else{
		msg('修改失败！','admin_list_edit.php');
	}
}
// 管理员修改资料
else if($act == 'profile'){

}
//删除管理员
else if ($act == 'del'){
	$id = $_GET['id'];
	if(empty($id)){
		msg('非法操作');
	}
	$sql ="delete from tk_admin where admin_id =$id";
	mysql_query($sql);
	if(mysql_affected_rows()>0){
		header('location: admin_list.php');
	}else{
		msg('删除失败!','admin_list.php');
	}
}
?>